<?php

class Model {

    private $pdo = null;
    private $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    private function connect_db()
    {
        if (!class_exists('PDO', false))
            throw new Exception("PHP PDO package is required.");

        if (empty($this->config))
            throw new Exception("Database definitions required.");

        $dsn = !empty($this->config['dsn']) ? $this->config['dsn'] : "{$this->config['type']}:host={$this->config['host']};dbname={$this->config['name']};charset={$this->config['charset']}";

        try
        {
            $this->pdo = new PDO(
                            $dsn,
                            $this->config['user'],
                            $this->config['pass'],
                            array(PDO::ATTR_PERSISTENT => !empty($this->config['persistent']) ? true : false)
            );
            $this->pdo->exec("SET CHARACTER SET {$this->config['charset']}");
        }
        catch (PDOException $e)
        {
            throw new Exception(sprintf("Can't connect to PDO database '{$this->config['type']}'. Error: %s", $e->getMessage()));
        }

        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    private function close_db()
    {
        $this->pdo = null;
    }

    public function get_blocks($page, $blocks_per_page, $mode = null)
    {
        $this->connect_db();

        $first_block = $page * $blocks_per_page;
        $blocks = array();
        $sql = "SELECT id_block, name_block, page_block, content_block, length_block, 
                date_format(date_block, '%d/%m/%Y') AS `date_block` FROM cms_blocks";
        if ($mode['page'] != 'default')
        {
            $sql .= " WHERE page_block = '" . $mode['page'] ."'";
            if ($mode['search'] != '')
            {
                $sql .= " AND (content_block LIKE '%" . $mode['search'] . "%') 
                        OR (name_block LIKE '%" . $mode['search'] . "%') 
                        OR (page_block LIKE '%" . $mode['search'] . "%')";
            }
        }
        else
        {
            if ($mode['search'] != '')
            {
                $sql .= " WHERE (content_block LIKE '%" . $mode['search'] . "%') 
                        OR (name_block LIKE '%" . $mode['search'] . "%') 
                        OR (page_block LIKE '%" . $mode['search'] . "%')";
            }
        }
        switch ($mode['order'])
        {
            case 'default':
                $sql .= " ORDER BY name_block";
                break;
            case 'page':
                $sql .= " ORDER BY page_block, name_block";
                break;
            case 'date':
                $sql .= " ORDER BY date_block DESC";
                break;
        }
        $sql .= " LIMIT " . $first_block . "," . $blocks_per_page;
        $query = $this->pdo->query($sql);
        while ($row = $query->fetch(PDO::FETCH_ASSOC))
        {
            $block['id'] = intval($row['id_block']);
            $block['name'] = htmlentities($row['name_block'], ENT_QUOTES, "UTF-8");
            $block['page'] = htmlentities($row['page_block'], ENT_QUOTES, "UTF-8");
            $block['content'] = htmlentities($row['content_block'], ENT_QUOTES, "UTF-8");
            $block['length'] = intval($row['length_block']);
            $block['date'] = htmlentities($row['date_block'], ENT_QUOTES, "UTF-8");
            $blocks[] = $block;
        }
        $this->close_db();
        return $blocks;
    }

    public function get_current_block($id)
    {
        $this->connect_db();
        $query = $this->pdo->prepare("SELECT * FROM cms_blocks WHERE id_block = ?");
        $query->execute(array($id));
        $block = $query->fetch(PDO::FETCH_ASSOC);
        $this->close_db();
        return $block;
    }

    public function delete_block($id)
    {
        $this->connect_db();
        $query = $this->pdo->prepare("DELETE FROM cms_blocks WHERE id_block = ?");
        $query->execute(array($id));
        if ($query->rowCount() == 0)
        {
            $return = false;
        }
        else
        {
            $return = true;
        }
        $this->close_db();
        return $return;
    }

    public function edit_block($id, $content)
    {
        $this->connect_db();
        $date = date("Y-m-d");
        $query = $this->pdo->prepare("UPDATE cms_blocks SET content_block = ?, date_block = ? WHERE id_block = ?");
        $query->execute(array($content, $date, $id));
        if ($query->rowCount() == 0)
        {
            $return = false;
        }
        else
        {
            $return = true;
        }
        $this->close_db();
        return $return;
    }

    public function block_count($mode = null)
    {
        $this->connect_db();
        $sql = "SELECT COUNT(*) AS `page_count` FROM cms_blocks";
        if ($mode['page'] != 'default')
        {
            $sql .= " WHERE page_block = '" . $mode['page'] ."'";
            if ($mode['search'] != '')
            {
                $sql .= " AND (content_block LIKE '%" . $mode['search'] . "%') 
                        OR (name_block LIKE '%" . $mode['search'] . "%') 
                        OR (page_block LIKE '%" . $mode['search'] . "%')";
            }
        }
        else
        {
            if ($mode['search'] != '')
            {
                $sql .= " WHERE (content_block LIKE '%" . $mode['search'] . "%') 
                        OR (name_block LIKE '%" . $mode['search'] . "%') 
                        OR (page_block LIKE '%" . $mode['search'] . "%')";
            }
        }
        $query = $this->pdo->query($sql);
        $count = $query->fetch(PDO::FETCH_ASSOC);
        $this->close_db();
        return $count['page_count'];
    }

    public function check_pass($pass)
    {
        $salted = $this->config['salt_prefix'] . $pass . $this->config['salt_suffix'];
        $hashed = hash("sha512", $salted);
        if ($this->config['connect_pass'] === $hashed)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    public function get_pages()
    {
        // Finir fonction
        $this->connect_db();
        $pages = array();
        $query = "SELECT DISTINCT `page_block` FROM `cms_blocks`";
        $result = $this->pdo->query($query);
        while ($row = $result->fetch(PDO::FETCH_ASSOC))
        {
            $pages[] = $row['page_block'];
        }
        $this->close_db();
        return $pages;
    }

}
